// const baseUrl = 'http://192.168.3.34:8080';//刘浩
const baseUrl = 'https://www.rzbygszbz.cn/apiI/'; //线上
import store from '../store/store'
import signMd5Utils from '@/common/signMd5Utils.js'
import {
	getUserLogin
} from '@/common/common.js'

function showToast(title) {
	uni.showToast({
		title: title,
		duration: 2000,
		icon: 'none'
	})
};

//opts请求设置 data请求参数 loading 是否显示loading{hideLoading,hideMsg}
const httpRequest = opts => {
	let token = uni.getStorageSync('userInfo').token
	let showLoading = opts.loading ? opts.loading.hideLoading : false // 是否显示 loading
	let showMsg = opts.loading ? opts.loading.hideMsg : true // 是否隐藏错误提示

	if (showLoading) {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
	}
	let sign = signMd5Utils.getSign(opts.url, opts.data);

	//配置默认请求头
	let _header = {
		'x-sign': sign,
		'X-TIMESTAMP': signMd5Utils.getTimestamp(),
		'X-Access-Token': token,
		'X-Requested-With': 'XMLHttpRequest',
		'Accept': 'application/json',
		'Content-Type': 'application/json; charset=UTF-8'
	}
	if (opts.header) {
		_header = {
			..._header,
			...opts.header
		}
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + opts.url,
			data: opts.data,
			method: opts.method,
			header: _header,
			dataType: 'json',
			success: async res => { // 服务器成功返回的回调函数
				if (showLoading) uni.hideLoading()
				if (res.statusCode === 200) {
					resolve(res)
					return
					if (showMsg) showToast(result.message)
				} else { // 返回值非 200，强制显示提示信息
					//未授权，token失效
					if (res.statusCode === 401) {
						const {
							token_s,
							status_s
						} = await getUserLogin();
						if (status_s) {
							_header['X-Access-Token'] = token_s
							uni.request({
								url: baseUrl + opts.url,
								data: opts.data,
								method: opts.method,
								header: _header,
								dataType: 'json',
								success: res => {
									if (showLoading) uni.hideLoading()
									if (res.statusCode === 200) {
										resolve(res)
										return
										if (showMsg) showToast(result.message)
									}
								}
							})
						}
					} else {
						showToast('[' + res.statusCode + '] 系统处理失败')
						reject('[' + res.statusCode + '] 系统处理失败')
					}
				}
			},
			fail: err => { // 接口调用失败的回调函数
				if (showLoading) uni.hideLoading()
				if (err.errMsg !== 'request:fail abort') {
					showToast('连接超时，请检查您的网络。')
					reject('连接超时，请检查您的网络。')
				}
			},
			complete: err => {
				if (showLoading) uni.hideLoading()

			}

		})
	})
}


export {
	baseUrl,
	httpRequest,
}